<?php

class Request {
	/**
	* $params 存post,get提交的数据
	*/
	public static  $params = array(
		'prefixes' => null,	
		'plugin' => null,
		'controller' => null,
		'action' => null,
		'id' => null,		
	);    
	/**
	* $data 存post[data]提交的数据
	*/
	public static  $data = array();
	/**
	* $query 存get提交的数据
	*/	
	public static  $query = array();
	
	public static  $sessionid = null;	
	
	public static  $hostinfo = null;
	
	public static  $secureport = null;	

	public static  $port = null;
	
	public static  $url = null;
	
	public static  $here = null;

	public static  $base = null;	
	
	public static  $querystring = null;
	
	public static  $scripturl = null;	
	
	public static  $requesturi = null;	
	
	public static function decodePathInfo($pathinfo){
		$pathinfo = urldecode($pathinfo);
		return $pathinfo;
/* 		//  utf8_encode() 函数把 ISO-8859-1 字符串编码为 UTF-8
		// http://w3.org/International/questions/qa-forms-utf-8.html
		if(preg_match('%^(?:
		   [\x09\x0A\x0D\x20-\x7E]            # ASCII
		 | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
		 | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
		 | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
		 | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
		 | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
		 | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
		 | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
		)*$%xs', $pathinfo))
		{
			return $pathinfo;
		} else {
			return utf8_encode($pathinfo);
		} */
	}
	
	public static function stripslashes_deep($values) {
	    if (is_array($values)) {
		    foreach ($values as $key => $value) {
			    $values[$key] = self::stripslashes_deep($value);
		    }
	    } else {
		    $values = stripslashes($values);
	    }
	    return $values;
    }	

	public static function getHostInfo(){
		if(self::$hostinfo===null) {
			if($secure=self::getIsSecureConnection()){
				$http='https';
			} else {
				$http='http';
			}	
			if(isset($_SERVER['HTTP_HOST'])) {
				self::$hostinfo=$http.'://'.$_SERVER['HTTP_HOST'];
			} else {			
				self::$hostinfo=$http.'://'.$_SERVER['SERVER_NAME'];
				$port=$secure ? self::getSecurePort() : self::getPort();
				if(($port!==80 && !$secure) || ($port!==443 && $secure)) {
					self::$hostinfo.=':'.$port;
				}	
			}
		}
		return self::$hostinfo;
	}
	
	public static function isAjax()	{
		return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
	}
/*
strcasecmp() 函数比较两个字符串。
该函数返回：
0 - 如果两个字符串相等
<0 - 如果 string1 小于 string2
>0 - 如果 string1 大于 string2
*/	
	public static function getIsSecureConnection() {
		return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
	}
	public static function getPort() {
		if(self::$port===null) {
			self::$port=!self::getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
		}	
		return self::$port;
	}
	public static function getSecurePort() {
		if(self::$secureport===null) {
			self::$secureport=self::getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
		}	
		return self::$secureport;
	}
	public static function getRestParams() {
		$result=array();
		if(function_exists('mb_parse_str')) {
			mb_parse_str(file_get_contents('php://input'), $result);
		} else {
			parse_str(file_get_contents('php://input'), $result);
		}	
		return $result;
	}	

	public static function getSiteURL() {
		if($secure=self::getIsSecureConnection()) {
		    $http='https';
		} else {
		    $http='http';
        }
		$http=$http .'://';			
        $url = $http . Param::read('siteURL');
		if(strpos(self::$here,$url)===false) {
            $allurl = Param::read('siteURLALL');		
		    $allurl = explode(",",$allurl);
			foreach($allurl as $u) {
			    if(strpos(self::$here,$http . $u)===0){
				    Param::write('siteURL', $u);
					break;
				}
			}
			$url = $http . Param::read('siteURL');
		}
		return $url;
	}		

	public static function Instance() {
		$DNS = self::DnsLocation();	
		$hostinfo = self::getHostInfo();
 /*
比如访问http://localhost:8080/psp/1.php/webroot/bar?ee=1
得到'http://localhost:8080'
*/	
		if(!empty($DNS['RequestUri']) || !empty($DNS['queryUrl'])){
			$hostinfo = self::getSiteURL();
			self::$hostinfo = $hostinfo;
		}		      
		$scripturl = self::getScriptUrl();
/*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到‘/psp/1.php’
*/			

		$requesturl = self::getRequestUri();
 /*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到'/webroot/bar'
*/		
        $t = trim($requesturl,'/');
		if(!empty($DNS['RequestUri']) && empty($t)){
			$requesturl = $DNS['RequestUri'];
		}
		$queryurl = self::getqueryUrl();
/*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到'ee=1'
*/		
		if(!empty($DNS['queryUrl'])){
			$queryurl .= '&'.$DNS['queryUrl'];
		}		
		$url = trim($hostinfo,'/').'/' . trim($scripturl,'/').'/' . trim($requesturl,'/') ;
		if($queryurl){
		    $url .= '?'.$queryurl ;
		}
		self::$here = $url ;		
        $url = self::getSiteURL();
        self::$base = $url ;		
        $url = $url. '/index.php';			
		self::$url = str_replace($url,'' , self::$here);			
        self::$url =  self::decodePathInfo(self::$url);				

		self::_processGet();
		self::_processPost();		
		self::_processFiles();
		self::_processParams();
		self::_SelectToSql();	
	}

  	public function DnsLocation() {//2,3,4级域名解析
		$domain = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : preg_replace("/([^:]*)[:0-9]*/i", "\\1", $_SERVER['HTTP_HOST']);
		$colums = array('test'=>'newhouse/index','newhouse'=>'newhouse/index','shangye'=>'shangye/index','subject'=>'subject/index','house'=>'sec/index','esf'=>'sec/index','bbs'=>'bbs/index','user'=>'user/index','ask'=>'ask/index','home'=>'decdefault/index','zx'=>'zx/index','video'=>'video/index','v'=>'video/index','map'=>'map/index','xingan'=>'town/index/?xian=875');
		$ww2 = array('0771'=>'97','0773'=>'98');
		$pixname = explode('.',$domain);
		$count = count($pixname);
        $DNS = array();
	    $DNS['queryUrl'] = '';
	    $DNS['RequestUri'] = '';        
		//print_r($pixname);exit;
		if($count==4){//三级域名比如newhouse.0773.guifun.com	
		    $column = $pixname[0];
		    $citywww = $pixname[1];
		    if(isset($colums[$column])){
			    $urlt = $colums[$column];
				if (strpos($urlt, '?') !== false) {					
					$urlts = filterEmptyVar(explode('?', $urlt));
					$num = 0 ;
					foreach($urlts as $k => $v){
						if($num==0){
							$DNS['RequestUri'] = $v;
						}else{
							$DNS['queryUrl'] .= $v.'&';
							$arr = explode('&', $v);
							foreach ($arr as $value) {
								if ($value) {
									$value = explode('=', $value);
									$_GET[$value[0]] = $value[1];
								}
							}							
						}
						if($num>10){
							break;
						}						
						$num++;
					}
				}else{
                    $DNS['RequestUri'] = $urlt;
				}	    
	        }	    
		    if(isset($ww2[$citywww])){
			    $_GET['cityid'] = $ww2[$citywww];
                $DNS['queryUrl'] .= '&cityid='.$ww2[$citywww];
	        }
		}else if($count==3 && $pixname[0]!='www'){
		    $host_name = $pixname[0];			
		    if(isset($ww2[$host_name])){//进入到分站首页比如0773.guifun.com	
                $DNS['RequestUri'] = 'default/index';			
                $DNS['queryUrl'] = 'cityid='.$ww2[$host_name];
                $_GET['cityid'] = $ww2[$host_name];
			}else if(isset($colums[$host_name])){//进入默认系统比如newhouse.guifun.com
			    $urlt = $colums[$host_name];
				if (strpos($urlt, '?') !== false) {					
					$urlts = filterEmptyVar(explode('?', $urlt));
					$num = 0 ;
					foreach($urlts as $k => $v){
						if($num==0){
							$DNS['RequestUri'] = $v;
						}else{
							$DNS['queryUrl'] .= $v.'&';
							$arr = explode('&', $v);
							foreach ($arr as $value) {
								if ($value) {
									$value = explode('=', $value);
									$_GET[$value[0]] = $value[1];
								}
							}							
						}
						if($num>10){
							break;
						}						
						$num++;
					}
				}else{
                    $DNS['RequestUri'] = $urlt;
				}
                $DNS['queryUrl'] .= '&cityid=98';
                $_GET['cityid'] = 98;                
			}else {//进入店铺二级域名比如shop0773.guifun.com或自定义phpscup.guifun.com
			    $connection = mysql_connect('10.146.66.16:3306', 'dbq53a663z7yb8fp', 'funingstyle123', true);
				mysql_select_db('guifun53a663z7', $connection);
		        if(strpos($host_name,'shop')===0){
				    $id = str_replace('shop','',$pixname[0]);
				    $id = intval($id);
				    $sql = "select s.shop_type from guifang_shop_info as s where id=".$id;
					$query =  mysql_query($sql, $connection);		
					$SHOP =mysql_fetch_array($query,MYSQL_ASSOC) ;
			        if(!empty($SHOP)){
                        $shoptype = $SHOP['shop_type'];	
				    }				    	            
		        } else {//用户自定义的二级域名
				    $shop_domain = $pixname[0];	
				    $sql = "select s.shop_type,s.id from guifang_shop_info as s where shop_domain='{$shop_domain}'";
					$query =  mysql_query($sql, $connection);		
					$SHOP =mysql_fetch_array($query,MYSQL_ASSOC) ;
			        if(!empty($SHOP)){
                        $shoptype = $SHOP['shop_type'];	
                        $id = $SHOP['id'];
				    }	        
		        }
				mysql_free_result($query);
				mysql_close($connection);		        
			    if($shoptype==1){//二手房
			        $DNS['RequestUri'] = "sec/shop/$id";
				}else if($shoptype==2){//新房
			        $DNS['RequestUri'] = "newshop/index/$id";				
			    }else if($shoptype==3){//建材店铺
			        $DNS['RequestUri'] = "decshop/index/$id";			    				   
			    }else if($shoptype==4){//装修店铺
			        $DNS['RequestUri'] = "renshop/index/$id";			    				   
				}else {
                    
				}   
			}    	
		}else if(($count==3 && $pixname[0]=='www')||$count==2){
		   
		}
		return $DNS;		
    }

	public static function RouterParse ($url=null) {
		return Router::parse($url);
	}

	public static function UpfileDir ($url,$isall=true) {
		$url = ltrim(ltrim($url,'/'),'\\');
	    if ($isall) {	
		    return self::$base .'/'. trim(Param::read('upfiles.path'),'/').'/'.$url;
		} else {
		    return '/'. trim(Param::read('upfiles.path'),'/').'/'.$url;
		}  
	}
	
	
	/*
	 get的sc数据格式是sc=sca.10scb.22
	*/	
	public static function _SelectToSql () {
	    $sc = self::get_args('sc');
		if($sc)	{		
			$filename = ucfirst(Request::$params['plugin']) . ucfirst(Request::$params['prefixes']) 
			. ucfirst(Request::$params['controller']) . ucfirst(Request::$params['action']) . '.php';			
			$file = CONFIGS . DS .'select'. DS . $filename ;
			if(file_exists($file)) {
			    $selectdata = include ($file);
				if(!empty($selectdata)) {
				    $sctempdata = filterEmptyVar(explode('sc', $sc));
				    $scdata = array();
				    $selectstr = '';
				    foreach($sctempdata as $key=>$value) {
						$temp = explode(".",$value);
						$scdata[$temp[0]] = $temp[1];
				    }
				    foreach($selectdata as $value) {
                        if(isset($scdata[$value['filedAlias']])&&isset($value['selectlist'])&&!empty($value['selectlist'])
						    && isset($value['selectlist'][$scdata[$value['filedAlias']]]) && isset($value['selectlist'][$scdata[$value['filedAlias']]]['conditions']) ) {							
							$selectstr.= ' '.$value['selectlist'][$scdata[$value['filedAlias']]]['conditions']." and";
					    }
				    }	
                    if (!defined("PSP_SC_SELECT_STR")) {
	                    define("PSP_SC_SELECT_STR", substr($selectstr, 0,-3));
	                    Param::write("PSP_SC_SELECT_STR", substr($selectstr, 0,-3));						
                    }				
				}				
			}
		} 
	}

	public static function _processPost() {
	    //对使用 <psp:form type='checkbox' > 这样的复选框标签的值进行处理
        $_POST = self::_checkboxFormFilter( $_POST );		
		if (ini_get('magic_quotes_gpc') === '1') {
			$_POST = self::stripslashes_deep($_POST);
		}	
		self::$data = $_POST;		
		if (self::_env('HTTP_X_HTTP_METHOD_OVERRIDE')) {
			self::$data['_method'] = self::_env('HTTP_X_HTTP_METHOD_OVERRIDE');
		}		
		if (isset(self::$data['_method'])) {
			if (!empty($_SERVER)) {
				$_SERVER['REQUEST_METHOD'] = self::$data['_method'];
			} else {
				$_ENV['REQUEST_METHOD'] = self::$data['_method'];
			}
			unset(self::$data['_method']);
		}		
        if(isset(self::$data['prefixes']) && !empty( self::$data['prefixes'] ) ) {
		    if ( $pkey = array_search(self::$data['prefixes'],Router::prefixes()) ) {
			    self::$query['prefixes'] = $pkey;
		    }
		}
        if(isset(self::$data['plugin']) && !empty( self::$data['plugin'] ) ) {
		    $_plugins = self::plugins();
			if(isset($_plugins[self::$data['plugin']])){
			    self::$query['plugin'] = self::$data['plugin']; 
            }
            unset($_plugins);			
		}		
        if(isset(self::$data['controller']) && !empty( self::$data['controller'] ) ) {
		    self::$query['controller'] = self::$data['controller']; 
		}		
        if(isset(self::$data['action']) && !empty( self::$data['action'] ) ) {
		    self::$query['action'] = self::$data['action']; 
		}		
        if(isset(self::$data[Param::read('Session.postOrGetIdName')]) && !empty( self::$data[Param::read('Session.postOrGetIdName')] ) ) {
		    self::$sessionid = self::$data[Param::read('Session.postOrGetIdName')]; 
		}		
		if (isset(self::$data['data'])) {
			$data = self::$data['data'];
			if (count(self::$data['data']) < 1) {
				self::$data = $data;
			} else {
				unset(self::$data['data']);
				self::$params = self::$params + self::$data; 
				self::$data = $data;
			}
		}		
	}
	
	//对使用 <psp:form type='checkbox' > 这样的复选框标签的值进行处理-----开始
	public static function _checkboxFormFilter($parray) {
	    if(is_array($parray)) {
		    foreach ($parray as $key => $value) {
		        if((strstr($key, '_psp_checkbox_form_') !== false) && is_array($value)){
			        unset($parray[$key]);
				    $parray[str_replace('_psp_checkbox_form_','',$key)] = self::__checkboxFormFilter('',$value);					
			    } else {
			        $parray[$key] = self::_checkboxFormFilter($parray[$key]);			
			    }
            }
        }		
		return $parray;
	}	
	
	public static function __checkboxFormFilter($str,$parray) {
        foreach ($parray as $key => $value) {	
		    if (!is_array($value)) { 
                $str .=" ".$value;
            }else {
                self::__checkboxFormFilter($str,$value);
		    }
		}
		return $str;
	}	
	//对使用 <psp:form type='checkbox' > 这样的复选框标签的值进行处理-----结束
	
	public static function _env($key) {
	    $val = null;
	    if (isset($_SERVER[$key])) {
		    $val = $_SERVER[$key];
	    } elseif (isset($_ENV[$key])) {
		    $val = $_ENV[$key];
	    } elseif (getenv($key) !== false) {
		    $val = getenv($key);
	    }
	    if ($val !== null) {
		    return $val;
	    }
	}

	public static function referer($default = null, $local = false) {
		$ref = self::_env('HTTP_REFERER');	
		if (!empty($ref) && self::$base) {
			$base = self::$base;
			if (strpos($ref, $base . '/index.php') === 0) {
				$return =  substr($ref, strlen($base. '/index.php'));
				if ($return[0] != '/') {
					$return = '/'.$return;
				}
				return $return;
			} else if(strpos($ref, $base) === 0) {
				$return =  substr($ref, strlen($base));
				if ($return[0] != '/') {
					$return = '/'.$return;
				}
				return $return;			
			} elseif (!$local) {
				return $ref;
			}
		}

		if ($default != null) {
			$url = Router::url($default, true);
			return $url;
		}
		return '/';
	}	
	
    //对表单的统一处理
	public static function get_args($name) {
	    if(isset($_GET[$name]))return $_GET[$name];
	    if(isset($_POST[$name]))return $_POST[$name];
	    return null;
    }

	public static function _processGet() {
		if (ini_get('magic_quotes_gpc') === '1') {
			$_GET = self::stripslashes_deep($_GET);
		}
		$query = $_GET;
		$query += self::RouterParse(self::$url);		
		$querystr = self::getqueryUrl();		
		parse_str($querystr, $queryArgs);
		$query += $queryArgs;
        if(isset($query[Param::read('Session.postOrGetIdName')]) && !empty( $query[Param::read('Session.postOrGetIdName')] ) ) {
		    self::$sessionid = $query[Param::read('Session.postOrGetIdName')]; 
		}			
		self::$query = $query;
	}
	
	public static function _processParams() {	
        if(isset(self::$query['prefixes']) && !empty( self::$query['prefixes'] ) ) {
			self::$params['prefixes'] = self::$query['prefixes'];
		}
        if(isset(self::$query['plugin']) && !empty( self::$query['plugin'] ) ) {
			self::$params['plugin'] = self::$query['plugin']; 		
		}		
        if(isset(self::$query['controller']) && !empty( self::$query['controller'] ) ) {
		    self::$params['controller'] = self::$query['controller']; 
		}		
        if(isset(self::$query['action']) && !empty( self::$query['action'] ) ) {
		    self::$params['action'] = self::$query['action']; 
		}		
        if(isset(self::$query['id']) && !empty( self::$query['id'] ) ) {
		    self::$params['id'] = self::$query['id']; 
		}		
	}
	
/**
http://localhost/psp/1.php/foo/bar.html?c=index&m=search
可以得到 
$_SERVER['PATH_INFO'] = '/foo/bar.html'
$_SERVER['QUERY_STRING'] = 'c=index&m=search';
$_SERVER['REQUEST_URI'] = '/psp/1.php/foo/bar.html?c=index&m=search';
$_SERVER['PHP_SELF'] = '/psp/1.php/foo/bar.html'
$_SERVER['SCRIPT_NAME'] = '/psp/1.php'

$_SERVER['REQUEST_URI']和$_SERVER["HTTP_X_REWRITE_URL"]区别
$_SERVER['REQUEST_URI']和$_SERVER["HTTP_X_REWRITE_URL"]这2个函数的功能都是得到访问此页面所需的URI，比如：
http://www.nbftp.cn/blog/index.php?id=99
他们得到的结果都是：/blog/index.php?id=99

区别在于$_SERVER['REQUEST_URI']在apache下有效，二$_SERVER["HTTP_X_REWRITE_URL"]在IIS下有效。

顺便提下，$_SERVER["QUERY_STRING"]，$_SERVER["REQUEST_URI"]，$_SERVER["SCRIPT_NAME"]，$_SERVER["PHP_SELF"]这4个变量的区别，用个例子来说明。

http://www.nbftp.cn/blog/index.php?id=99

1、$_SERVER["QUERY_STRING"]：得到到前页面的查询字符串：id=99

2、$_SERVER["REQUEST_URI"]：得到当前页面的uri：/blog/index.php?id=99

3、$_SERVER["SCRIPT_NAME"]：得到到前页面的脚本路径：/blog/index.php

4、$_SERVER["PHP_SELF"]：得到正在执行的脚本文件名：/blog/index.php

$_SERVER['argv']是一个只有一个元素的数组, 内容为URL的问号之后的字符串.
例如: a.php?a=1&b=2&c=3&d=4
则 $_SERVER['argv'] 的值为:
array (
0 => 'a=1&b=2&c=3&d=4'
)
这时候 $_SERVER['argc'] 的值为整数 1.
如果没有问号或者问号后面为空, 则 $_SERVER['argv'] 为空数组, 值为 array(), 而 $_SERVER['argc'] 值为整数 0.

 */
 /*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到'/webroot/bar'
*/
	public static function getRequestUri() {

		if (self::$requesturi !== null) {
			return self::$requesturi;
		}		
		if (!empty($_SERVER['PATH_INFO'])) {
			return $_SERVER['PATH_INFO'];
		} elseif (isset($_SERVER['REQUEST_URI'])) {
			$uri = $_SERVER['REQUEST_URI'];	
			
			if(!empty($_SERVER['HTTP_HOST'])){
			
				if(strpos($uri,$_SERVER['HTTP_HOST'])!==false){
					$uri=preg_replace('/^\w+:\/\/[^\/]+/','',$uri);
				}	
			}
			else {
				$uri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$uri);
			}
			if( strpos($_SERVER['HTTP_HOST'].$uri,Param::read('siteURL'))!==false){
			    $uri = '';
			}
		} elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SCRIPT_NAME'])) {
			$uri = str_replace($_SERVER['SCRIPT_NAME'], '', $_SERVER['PHP_SELF']);
		} elseif (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
			$uri = $_SERVER['HTTP_X_REWRITE_URL'];
		} elseif (isset($_SERVER['ORIG_PATH_INFO'])) {
		    $uri = $_SERVER['ORIG_PATH_INFO']; 
			if(!empty($_SERVER['QUERY_STRING'])){
			$uri.='?'.$_SERVER['QUERY_STRING'];
			}
		} elseif (isset($_SERVER['argv'])) {
		    $uri = $_SERVER['argv'][0];
	    } elseif (isset($_ENV['argv'])) {
		    $uri = $_ENV['argv'];
	    } elseif (getenv('argv') !== false) {
		    $uri = getenv('argv');
	    }			
		$ScriptUrl = self::getScriptUrl();
		if (strlen($ScriptUrl) > 0 ) {
			$uri = str_replace($ScriptUrl,'',$uri);
		}		
		if (strpos($uri, '?') !== false) {
			list($uri) = explode('?', $uri, 2);
		}
		if (empty($uri) || $uri == '/' || $uri == '//') {
			return '/';
		}
		return self::inflectorUrl($uri);
	}

/*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到‘/psp/1.php’
*/
	public static function getScriptUrl() {
		if(self::$scripturl===null)	{
			$scriptName=basename($_SERVER['SCRIPT_FILENAME']);
			if(basename($_SERVER['SCRIPT_NAME'])===$scriptName){
				self::$scripturl=$_SERVER['SCRIPT_NAME'];
			}else if(basename($_SERVER['PHP_SELF'])===$scriptName){
				self::$scripturl=$_SERVER['PHP_SELF'];
			}else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName){
				self::$scripturl=$_SERVER['ORIG_SCRIPT_NAME'];
			}else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false){
				self::$scripturl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
			}else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0){
				self::$scripturl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
			}else{
				exit('Request is unable to determine the entry script URL.');
			}	
			self::$scripturl = self::inflectorUrl(self::$scripturl);	
		}		
		return self::$scripturl;
	}
/*
比如访问http://localhost/psp/1.php/webroot/bar?ee=1
得到'ee=1'
*/
	public static function getqueryUrl() {
	    if(self::$querystring === null) {
	        if (isset($_SERVER['REQUEST_URI'])) {
			    $uri = $_SERVER['REQUEST_URI'];
		        if (strpos($uri, '?') !== false) {
			    list(, $querystr) = explode('?', $uri);
				self::$querystring = $querystr;
		        }                				
		    }			      
		}
		return self::$querystring;
	}
	
	public static function inflectorUrl($value)
	{
		return '/'.trim($value,'/');
	}



	public static function _processFiles() {
		if (isset($_FILES) && is_array($_FILES)) {
			foreach ($_FILES as $name => $data) {
				if ($name != 'data') {
					self::$params['form'][$name] = $data;
				}
			}
		}

		if (isset($_FILES['data'])) {
			foreach ($_FILES['data'] as $key => $data) {
				foreach ($data as $model => $fields) {
					if (is_array($fields)) {
						foreach ($fields as $field => $value) {
							if (is_array($value)) {
								foreach ($value as $k => $v) {
									self::$data[$model][$field][$k][$key] = $v;
								}
							} else {
								self::$data[$model][$field][$key] = $value;
							}
						}
					} else {
						self::$data[$model][$key] = $fields;
					}
				}
			}
		}
	}


	public static function getclientIp($safe = true) {
		if (!$safe && self::_env('HTTP_X_FORWARDED_FOR') != null) {
			$ipaddr = preg_replace('/(?:,.*)/', '', self::_env('HTTP_X_FORWARDED_FOR'));
		} else {
			if (self::_env('HTTP_CLIENT_IP') != null) {
				$ipaddr = self::_env('HTTP_CLIENT_IP');
			} else {
				$var = self::_env('REMOTE_ADDR');
	            if ( $var === self::_env('SERVER_ADDR')) {
		            $addr = self::_env('HTTP_PC_REMOTE_ADDR');
		            if ($addr !== null) {
			          $var = $addr;
		            }
	            }				
				$ipaddr = $var ;
			}
		}

		if (self::_env('HTTP_CLIENTADDRESS') != null) {
			$tmpipaddr = self::_env('HTTP_CLIENTADDRESS');
			if (!empty($tmpipaddr)) {
				$ipaddr = preg_replace('/(?:,.*)/', '', $tmpipaddr);
			}
		}
		return trim($ipaddr);
	}

	public static function acceptLanguage($language = null) {
		$accepts = preg_split('/[;,]/', self::_env('HTTP_ACCEPT_LANGUAGE'));
		foreach ($accepts as &$accept) {
			$accept = strtolower($accept);
			if (strpos($accept, '_') !== false) {
				$accept = str_replace('_', '-', $accept);
			}
		}
		if ($language === null) {
			return $accepts;
		}
		return in_array($language, $accepts);
	}

	function getBrowse()
	{
		global $_SERVER;
		$Agent = $_SERVER['HTTP_USER_AGENT'];
		$browseinfo='';
		if(ereg('Mozilla', $Agent) && !ereg('MSIE', $Agent)){
		$browseinfo = 'Netscape Navigator';
		}
		if(ereg('Opera', $Agent)) {
		$browseinfo = 'Opera';
		}
		if(ereg('Mozilla', $Agent) && ereg('MSIE', $Agent)){

		$browseinfo = 'Internet Explorer';
		}
		if(ereg('Chrome', $Agent)){
		$browseinfo="Chrome";
		}
		if(ereg('Firefox', $Agent)){
		$browseinfo="Firefox";
		}

		return $browseinfo;
	}

	function getOS ()
	{
		global $_SERVER;
		$agent = $_SERVER['HTTP_USER_AGENT'];
		$os = false;
		if (eregi('win', $agent) && strpos($agent, '95')){
		$os = 'Windows 95';
		}
		else if (eregi('win 9x', $agent) && strpos($agent, '4.90')){
		$os = 'Windows ME';
		}
		else if (eregi('win', $agent) && ereg('98', $agent)){
		$os = 'Windows 98';
		}
		else if (eregi('win', $agent) && eregi('nt 5.1', $agent)){
		$os = 'Windows XP';
		}
		else if (eregi('win', $agent) && eregi('nt 5.2', $agent)){
		$os = 'Windows 2003';
		}
		else if (eregi('win', $agent) && eregi('nt 5', $agent)){
		$os = 'Windows 2000';
		}
		else if (eregi('win', $agent) && eregi('nt', $agent)){
		$os = 'Windows NT';
		}
		else if (eregi('win', $agent) && ereg('32', $agent)){
		$os = 'Windows 32';
		}
		else if (eregi('linux', $agent)){
		$os = 'Linux';
		}
		else if (eregi('unix', $agent)){
		$os = 'Unix';
		}
		else if (eregi('sun', $agent) && eregi('os', $agent)){
		$os = 'SunOS';
		}
		else if (eregi('ibm', $agent) && eregi('os', $agent)){
		$os = 'IBM OS/2';
		}
		else if (eregi('Mac', $agent) && eregi('PC', $agent)){
		$os = 'Macintosh';
		}
		else if (eregi('PowerPC', $agent)){
		$os = 'PowerPC';
		}
		else if (eregi('AIX', $agent)){
		$os = 'AIX';
		}
		else if (eregi('HPUX', $agent)){
		$os = 'HPUX';
		}
		else if (eregi('NetBSD', $agent)){
		$os = 'NetBSD';
		}
		else if (eregi('BSD', $agent)){
		$os = 'BSD';
		}
		else if (ereg('OSF1', $agent)){
		$os = 'OSF1';
		}
		else if (ereg('IRIX', $agent)){
		$os = 'IRIX';
		}
		else if (eregi('FreeBSD', $agent)){
		$os = 'FreeBSD';
		}
		else if (eregi('teleport', $agent)){
		$os = 'teleport';
		}
		else if (eregi('flashget', $agent)){
		$os = 'flashget';
		}
		else if (eregi('webzip', $agent)){
		$os = 'webzip';
		}
		else if (eregi('offline', $agent)){
		$os = 'offline';
		}
		else {
		$os = 'Unknown';
		}
		return $os;
	}	
	
	
}

?>